package com.rabbit.conf;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author CKC
 * @date 2022/12/25 11:19
 */
@Configuration
public class RabbitMQConf {

    public static final String topicExchange = "topicExchange1";
    public static final String deadExchange = "deadExchange";

    public static final String deadQueue = "deadQueue";
    public static final String topicQueue = "topicQueue1";

    /**
     * 消息->交换机 回调函数
     * ack:true 发送成功 false: 发送失败
     */
    private final RabbitTemplate.ConfirmCallback confirmCallback = (correlationData, ack, cause) -> {
        if (!ack) {
            System.out.println("发送消息失败， Cause:" + cause);
        }
    };
    /**
     * 交换机->消息队列 回调函数
     * 发送失败：触发returnCallback回调函数
     */
    private final RabbitTemplate.ReturnCallback returnCallback = (message, replyCode, replyText, exchange, routingKey) ->
            System.out.printf("sendMsg:=======> Exchange To Queue Failed! Message:%s Exchange:%s RoutingKey:%s Replay:%s ", message, exchange, routingKey, replyText);

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        rabbitTemplate.setConfirmCallback(confirmCallback);
        rabbitTemplate.setReturnCallback(returnCallback);
        return rabbitTemplate;
    }

    //1.交换机
    @Bean("exchange1")
    public Exchange myExchange() {
        return ExchangeBuilder
                .topicExchange(topicExchange)
                .durable(true)
                .autoDelete()
                .build();
    }


    //2.队列
    @Bean("queue1")
    public Queue myQueue() {
        return QueueBuilder
                .nonDurable(topicQueue)
                .autoDelete()
                .ttl(10000)
                .deadLetterRoutingKey("dead")//死信队列路由key
                .deadLetterExchange(deadExchange)//死信队列交换机
                .build();
    }

    //3.队列与交换机绑定
    @Bean
    public Binding bindQueueExchange(@Qualifier("queue1") Queue queue, @Qualifier("exchange1") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("user.#").noargs();
    }



    @Bean
    public Exchange deadExchange() {
        return ExchangeBuilder.directExchange(deadExchange).durable(false).autoDelete().build();
    }

    @Bean
    public Queue deadQueue() {
        return QueueBuilder.nonDurable(deadQueue).ttl(1000).autoDelete().build();
    }

    @Bean
    public Binding deadBindQueueExchange(Queue deadQueue, Exchange deadExchange) {
        return BindingBuilder.bind(deadQueue).to(deadExchange).with("dead").noargs();
    }


}
